package controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.persistence.EntityManager;

import model.CapDo;
import model.ChiTietHoaDon_Sach;
import model.ChiTietHoaDon_SachID;
import model.HoaDon;
import model.NguoiDung;
import model.Sach;

import org.hibernate.criterion.Restrictions;
import org.zkoss.bind.annotation.BindingParam;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.ContextParam;
import org.zkoss.bind.annotation.ContextType;
import org.zkoss.bind.annotation.Init;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.WrongValueException;
import org.zkoss.zk.ui.select.SelectorComposer;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zk.ui.util.Composer;
import org.zkoss.zul.Window;

import dao.DatabaseConnector;
import dao.entity.CapDoDAO;
import dao.entity.ChiTietHoaDon_SachDAO;
import dao.entity.HoaDonDAO;
import dao.entity.NguoiDungDAO;

public class ShoppingCart extends SelectorComposer<Component> {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String hinh;
	private String tenSach;
	private int soLuongBan;
	private String hoTen;
	private String diaChi;
	private String sdt;

	public String getHoTen() {
		String email = (String) Sessions.getCurrent().getAttribute("email");
		NguoiDungDAO dao = new NguoiDungDAO();
		List<NguoiDung> list = dao.findByCriteria(Restrictions.eq("email",
				email));
		if (list != null) {
			hoTen = list.get(0).getTenNguoiDung();
			diaChi = list.get(0).getDiaChi();
			sdt = list.get(0).getSoDienThoai();
		}

		return hoTen;
	}

	public String getDiaChi() {
		return diaChi;
	}

	public String getSdt() {
		return sdt;
	}

	public int getSoLuongBan() {
		soLuongBan = 1;
		return soLuongBan;
	}

	public void setSoLuongBan(int soLuongBan) {
		this.soLuongBan = soLuongBan;
	}

	public String getHinh() {
		return hinh;
	}

	public void setHinh(String hinh) {
		this.hinh = hinh;
	}

	public String getTenSach() {
		return tenSach;
	}

	public void setTenSach(String tenSach) {
		this.tenSach = tenSach;
	}

	Sach sach = new Sach();

	List<Integer> listIDSach = new ArrayList<>();

	List<Sach> listSach = new ArrayList<Sach>();

	private Sach sach1;

	HashMap<Integer, Sach> map = new HashMap<Integer, Sach>();

	@Init
	public void addListSach(@ContextParam(ContextType.VIEW) Component view) {
		map = (HashMap<Integer, Sach>) Sessions.getCurrent().getAttribute(
				"gioHang");

		for (Integer key : map.keySet()) {
			listIDSach.add(key);
		}

		for (int i = 0; i < listIDSach.size(); i++) {
			if (map.containsKey(listIDSach.get(i))) {
				if (!listIDSach.contains(map)) {
					sach1 = (Sach) map.get(listIDSach.get(i));
					listSach.add(sach1);
				}
			}
		}

	}

	@Command
	public void removeItem(@BindingParam("deleteSachCart") Sach sach) {
		map = (HashMap<Integer, Sach>) Sessions.getCurrent().getAttribute(
				"gioHang");

		map.remove(sach.getId_Sach());

		Executions.sendRedirect("thanh_toan_form.zul");
	}

	// @SuppressWarnings("unchecked")
	public List<Sach> getListSachCart() {
		return listSach;
	}

	int dem = sach.getSoLuongBan();

	@Command
	public void buttonTang(@BindingParam("buttonTang") Sach sach) {
		sach.setSoLuongBan(sach.getSoLuongBan() + 1);
		Executions.sendRedirect("");
		// sach.g
		// soLuongBan = soLuongBan + 1;
	}

	@Command
	public void buttonGiam(@BindingParam("buttonGiam") Sach sach) {
		if (sach.getSoLuongBan() == 1) {
			// map = (HashMap<Integer, Sach>)
			// Sessions.getCurrent().getAttribute(
			// "gioHang");
			// map.remove(sach.getId_Sach());

			removeItem(sach);
			Executions.sendRedirect("");
		} else {
			sach.setSoLuongBan(sach.getSoLuongBan() - 1);
			Executions.sendRedirect("");
			// soLuongBan = soLuongBan - 1;
		}
	}

	private float tongTien;

	public float getSumMoney() {
		map = (HashMap<Integer, Sach>) Sessions.getCurrent().getAttribute(
				"gioHang");
		float count = 0;
		for (Integer key : map.keySet()) {
			count += map.get(key).getGiaBan() * map.get(key).getSoLuongBan();
		}
		return count;
	}

	NguoiDung nguoiDung = new NguoiDung();

	String emailNguoiDung;
	// Lay gio he thong
	Date thoiGian = new Date();

	// Khai bao dinh dang ngay thang
	SimpleDateFormat dinhDangThoiGian = new SimpleDateFormat(
			"HH:mm:ss dd/MM/yyyy ");

	// parse ngay thang sang dinh dang va chuyen thanh string.
	String hienThiThoiGian = dinhDangThoiGian.format(thoiGian.getTime());

	@Listen("onClick = #buttonThanhToan")
	public void thanhToan() {
		System.out.println("Da click thanh thoan");

		System.out.println("SoLuongBan: " + sach.getSoLuongBan());
		emailNguoiDung = (String) Sessions.getCurrent().getAttribute("email");
		NguoiDungDAO dao = new NguoiDungDAO();
		List<NguoiDung> list = dao.findByCriteria(Restrictions.eq("email",
				emailNguoiDung));

		HoaDonDAO hoaDonDAO = new HoaDonDAO();
		HoaDon hoaDon = new HoaDon(hienThiThoiGian, list.get(0)
				.getSoDienThoai(), list.get(0).getDiaChi(), getSumMoney(), list
				.get(0).getTenNguoiDung());
		NguoiDung nd = new NguoiDung();
		nd.setId_NguoiDung(list.get(0).getId_NguoiDung());
		hoaDon.setNguoiDung(nd);
		hoaDonDAO.persist(hoaDon);
		// Executions.sendRedirect("thanhToanThanhCong.zul");

		map = (HashMap<Integer, Sach>) Sessions.getCurrent().getAttribute(
				"gioHang");
		EntityManager em = DatabaseConnector.getEntityManager();
		for (Integer key : map.keySet()) {
			int SoLuongCon = map.get(key).getSoLuong()
					- map.get(key).getSoLuongBan();
			Sach sach = em.find(Sach.class, map.get(key).getId_Sach());
			try {
				em.getTransaction().begin();
				sach.setSoLuongBan(1);
				sach.setSoLuong(SoLuongCon);
				em.getTransaction().commit();
			} catch (Exception e) {
				em.getTransaction().rollback();
			}

		}
		addChiTietHoaDon(map, emailNguoiDung);
		Sessions.getCurrent().removeAttribute("gioHang");
		Executions.sendRedirect("shoppingcart.zul?target=thanhcong");

		// Sessions.getCurrent().setAttribute("email", email_nguoiDung);
		// Executions.sendRedirect("thanhToanThanhCong.zul");
	}

	private void addChiTietHoaDon(HashMap<Integer, Sach> map2,
			String emailNguoiDung2) {
		NguoiDungDAO dao = new NguoiDungDAO();
		List<NguoiDung> list = dao.findByCriteria(Restrictions.eq("email",
				emailNguoiDung));
		int idNguoiDung = list.get(0).getId_NguoiDung(); // lay dc id nguoi dung
		System.out.println(idNguoiDung);
		NguoiDung nd = new NguoiDung();
		nd.setId_NguoiDung(idNguoiDung); // set lai id nguoi dung

		HoaDonDAO hdDAO = new HoaDonDAO();
		List<HoaDon> listHD = hdDAO.findByCriteria(Restrictions.eq("nguoiDung",
				nd));
		int idHD = listHD.get(listHD.size() - 1).getId_HoaDon();
		System.out.println(idHD);

		for (Integer key : map.keySet()) {
			ChiTietHoaDon_SachID hd_id = new ChiTietHoaDon_SachID(idHD, map
					.get(key).getId_Sach());
			ChiTietHoaDon_Sach hd_sach = new ChiTietHoaDon_Sach();
			hd_sach.setChiTietHoaDon_SachID(hd_id);
			ChiTietHoaDon_SachDAO daoHoaDon = new ChiTietHoaDon_SachDAO();
			daoHoaDon.persist(hd_sach);
		}
	}

	@Listen("onClick = #buttonTiepTucMuaHang")
	public void tiepTucMuaHang() {
		Executions.sendRedirect("index.zul");
	}

	@Listen("onClick = #buttonThanhToan0")
	public void xacNhanThanhToan() {
		emailNguoiDung = (String) Sessions.getCurrent().getAttribute("email");
		if (emailNguoiDung == null) {
			Window window = (Window) Executions.createComponents(
					"form_login.zul", null, null);
			window.doModal();
		} else {
			Executions.sendRedirect("shoppingcart.zul?target=xacnhanthanhtoan");
		}
	}
	/*
	 * @Listen("onClick = #troVetrangChu") public void troVeTrangChu(){
	 * Executions.sendRedirect("index.zul"); }
	 */
}
